package com.feicheng.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feicheng.base.batch.IntoBatch;
import com.feicheng.base.common.DaoConstant;
import com.feicheng.base.exception.SystemException;
import com.feicheng.base.result.Result;
import com.feicheng.entity.IntoHeader;
import com.feicheng.entity.IntoItem;
import com.feicheng.entity.PurchaseHeader;
import com.feicheng.entity.Stock;
import com.feicheng.model.*;
import com.feicheng.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author guihai.yu
 * @since 2022-07-04
 */
@RestController
@RequestMapping("/into")
public class IntoHeaderController {

    /* 依赖注入入库订单头service*/
    @Autowired
    IIntoHeaderService iIntoHeaderService;

    /* 依赖注入入库订单体service*/
    @Autowired
    IIntoItemService iIntoItemService;

    /* 依赖注入采购订单头service*/
    @Autowired
    IPurchaseHeaderService iPurchaseHeaderService;

    /* 依赖注入库存service*/
    @Autowired
    IStockService iStockService;

    //注入用户Service
    @Autowired
    IUserService iUserService;

    /**
     * 入库列表条件分页
     * @param current 当前页码
     * @param size 10
     * @param intoHeaderWithItem
     * @anthor hao.zhang
     * @return
     */
    @PostMapping("/page")
    public Result selectIntoPage(@RequestParam(defaultValue = "1") Integer current,
                                 @RequestParam(defaultValue = "10") Integer size,
                                 @RequestBody IntoHeaderWithItem intoHeaderWithItem) {

        Page<IntoHeaderWithItem> page = new Page<>(current, size);
        QueryWrapper<IntoHeaderWithItem> intoHeaderQueryWrapper = new QueryWrapper<>();

        //名字查询
        if(StringUtils.hasLength(intoHeaderWithItem.getUserName())){
            intoHeaderQueryWrapper.like(DaoConstant.MODEL.INTOHEADER_WITH_ITEM.USER_NAME, intoHeaderWithItem.getUserName());
        }

        //仓库名查询
        if(null != intoHeaderWithItem.getWarehouseName()) {
            intoHeaderQueryWrapper.like(DaoConstant.MODEL.INTOHEADER_WITH_ITEM.WAREHOUSE_NAME, intoHeaderWithItem.getWarehouseName());
        }

        //时间查询
        if(null != intoHeaderWithItem.getStatuDate()) {
            intoHeaderQueryWrapper.ge(DaoConstant.MODEL.INTOHEADER_WITH_ITEM.STATEDATE, intoHeaderWithItem.getIntoWarehouseDate());
        }
        if(null != intoHeaderWithItem.getEndDate()) {
            intoHeaderQueryWrapper.le(DaoConstant.MODEL.INTOHEADER_WITH_ITEM.ENDDATE, intoHeaderWithItem.getIntoWarehouseDate());
        }

        //入库批次号查询
        if(null != intoHeaderWithItem.getBatchNo()) {
            intoHeaderQueryWrapper.eq(DaoConstant.INTO_HEADER.BATCH_NO, intoHeaderWithItem.getBatchNo());
        }

        //订单批次号查询
        if(null != intoHeaderWithItem.getPbatch()) {
            intoHeaderQueryWrapper.eq(DaoConstant.MODEL.INTOHEADER_WITH_ITEM.PBATCH, intoHeaderWithItem.getPbatch());
        }

        //返回查询结果
        return Result.success(iIntoHeaderService.selectIntoPage(page, intoHeaderQueryWrapper));
    }

    /**
     * 新增入库接口
     * @param intoHeaderIntoItem 入库信息
     * @author guihai.yu
     * @return
     */
    @PostMapping("/info")
    @Transactional
    public Result insertInto(@RequestBody IntoHeaderIntoItem intoHeaderIntoItem) {

        //采购批次号非空验证
        if (null == intoHeaderIntoItem.getPbatchNo()){
            //TODO
            throw new SystemException("采购批次号不能为空");
        }

        //根据采购批次号查询采购头表订单ID  因为他俩不可能重复     创建
        QueryWrapper<PurchaseHeader> queryWrapper = new QueryWrapper<>();

        //条件
        queryWrapper.eq(DaoConstant.PURCHASE_HEADER.BATCH_NO, intoHeaderIntoItem.getPbatchNo());
        //查询采购头结果
        List<PurchaseHeader> purchaseHeaderId = iPurchaseHeaderService.list(queryWrapper);

        //对应仓库id非空验证
        if (null == intoHeaderIntoItem.getWarehouseId()){
            //TODO
            throw new SystemException("对应仓库id不能为空");
        }

        //员工信息非空验证
        if (null == intoHeaderIntoItem.getUserId()){
            //TODO
            throw new SystemException("员工信息不能为空");
        }

        //门店id非空验证
        if (null == intoHeaderIntoItem.getUserId()){
            //TODO
            throw new SystemException("门店id不能为空");
        }

        //产品信息非空验证
        if (0 == intoHeaderIntoItem.getIntoItemPurchaseItem().length()){
            //TODO
            throw new SystemException("产品信息不能为空");
        }

        //将接收到的字符串转换为json数组
        JSONArray jsonArray =
                JSONArray.parseArray(intoHeaderIntoItem.getIntoItemPurchaseItem());

        //将json数组转换为list集合
        List<IntoItemPurchaseItem> intoItemPurchaseItems =
                jsonArray.toJavaList(IntoItemPurchaseItem.class);

        //for循环判断入库体内容是否为空
        for (int i = 0; i < intoItemPurchaseItems.size(); i++) {
            //入库体产品型号id非空验证
            if (null == intoItemPurchaseItems.get(i).getProductId()){
                //TODO
                throw new SystemException("入库体产品型号id不能为空");
            }

            //入库体入库商品数量非空验证
            if (null == intoItemPurchaseItems.get(i).getIntoProductNum()){
                //TODO
                throw new SystemException("入库体入库商品数量不能为空");
            }

        }

        //获取当前时间
        LocalDateTime localDateTime = LocalDateTime.now();

        //获取当前时间
        intoHeaderIntoItem.setIntoWarehouseDate(localDateTime);

        //获取入库批次号
        intoHeaderIntoItem.setBatchNo(IntoBatch.getBatch(intoHeaderIntoItem.getUserId(), intoHeaderIntoItem.getStoreId()).toString());

        //获取采购订单id
        intoHeaderIntoItem.setPurchaseHeaderId(purchaseHeaderId.get(0).getPurchaseHeaderId());

        //获取对应仓库id
        intoHeaderIntoItem.setWarehouseId(intoHeaderIntoItem.getWarehouseId());

        //获取员工信息id
        intoHeaderIntoItem.setUserId(intoHeaderIntoItem.getUserId());

        //将数据加入数据库
        boolean save = iIntoHeaderService.save(intoHeaderIntoItem);
        if (save){
            /**
             * 入库头添加成功后添加入库体
             */

            //创建入库订单体list集合
            List<IntoItem> intoItems = new ArrayList<>();

            //for循环把入库体需要的三条字段提出来
            for (int i = 0; i < intoItemPurchaseItems.size(); i++) {

                IntoItem intoItem = new IntoItem();
                IntoItemPurchaseItem intoItemPurchaseItem = intoItemPurchaseItems.get(i);

                //添加入库头id
                intoItem.setIntoHeaderId(intoItemPurchaseItem.getIntoHeaderId());

                //添加入库数量
                intoItem.setIntoProductNum(intoItemPurchaseItem.getIntoProductNum());

                //添加入库产品id
                intoItem.setProductId(intoItemPurchaseItem.getProductId());

                //放到集合里
                intoItems.add(intoItem);

            }

            //获取list集合，将入库订单头编号插入
            for (IntoItem intoItem : intoItems) {

                intoItem.setIntoHeaderId(intoHeaderIntoItem.getIntoHeaderId());
            }

            //保存信息,返回执行结果
            iIntoItemService.saveBatch(intoItems);
        }else {

            return Result.fail("添加失败",iIntoHeaderService);
        }


        //循环采购的商品，修改新增库存数量
        for (int i = 0; i <intoItemPurchaseItems.size() ; i++) {

            //根据仓库id 产品型号id  查询   创建
            QueryWrapper<Stock> stockQueryWrapper = new QueryWrapper<>();

            //条件，每次循环查询有没有符合的有就修改数量，没有就添加；
            stockQueryWrapper.eq(DaoConstant.STOCK.WAREHOUSE_ID,intoHeaderIntoItem.getWarehouseId())
                    .eq(DaoConstant.STOCK.PRODUCT_ID,intoItemPurchaseItems.get(i).getProductId());

            //查询采购头结果赋值给外边
            //查询的库存结果
            List<Stock> stockList = iStockService.list(stockQueryWrapper);

            //看是否查到数据查到只修改库存数量，没查到新增
            if (0 < stockList.size()) {

                for (int j = 0; j < stockList.size(); j++) {

                    //判断相等时修改
                    if (stockList.get(j).getWarehouseId() == intoHeaderIntoItem.getWarehouseId()
                            && stockList.get(j).getProductId() == intoItemPurchaseItems.get(i).getProductId()){

                        //创建入库对象
                        Stock stock = new Stock();

                        //获取库存id
                        stock.setStockId(stockList.get(j).getStockId());

                        //获取产品型号id
                        stock.setProductId(stockList.get(j).getProductId());

                        //获取产品数量
                        stock.setNum(stockList.get(j).getNum() + intoItemPurchaseItems.get(i).getIntoProductNum());

                        //获取仓库id
                        stock.setWarehouseId(stockList.get(j).getWarehouseId());

                        //将数据加入数据库
                        iStockService.updateById(stock);

                    }
                }

            } else {

                //仓库里不存在采购的商品，新增
                //创建入库对象
                Stock stock2 = new Stock();

                //获取产品型号id
                stock2.setProductId(intoItemPurchaseItems.get(i).getProductId());

                //获取产品数量
                stock2.setNum(intoItemPurchaseItems.get(i).getIntoProductNum());

                //获取仓库id
                stock2.setWarehouseId(intoHeaderIntoItem.getWarehouseId());

                //将数据加入数据库
                iStockService.save(stock2);

            }
        }
        return Result.success("添加成功");

    }

    /**
     * 入库查询详情
     * @param current 当前页
     * @param size 每页条数
     * @param intoHeaderId 入库头ID
     * @author yvan.yao
     * @return
     * @since 2022-07-04
     */
    @PostMapping("/detail/page/g")
    public Result getIntoHeader(Integer intoHeaderId,
                                @RequestParam(defaultValue = "1") Integer current,
                                @RequestParam(defaultValue = "10") Integer size
    ) {
        // 当入库头编号是空的时候
        if (null == intoHeaderId) {

            throw new SystemException("缺少主键");
        }

        // 构造条件查询
        QueryWrapper<IntoWithPurchase> intoDetailQueryWrapper = new QueryWrapper<>();

        // 把编号当做条件，放在构造器查询
        intoDetailQueryWrapper.eq(DaoConstant.INTO_HEADER.INTO_HEADER_ID,intoHeaderId);

        // 根据条件查询数据
        IntoWithPurchase intoDetail = iIntoHeaderService.selectIntodetail(intoDetailQueryWrapper);

        // 创建结果集
        JSONObject result = new JSONObject();

        // 查询数据放入结果集
        result.put(DaoConstant.MODEL.INTOWITHPURCHASE.MODEL_NAME,intoDetail);

        // 构建分页
        Page<ProductWithNumber> page = new Page<>(current,size);

        // 构建查询条件
        QueryWrapper<ProductWithNumber> productWithNumberQueryWrapper = new QueryWrapper<>();

        // 把编号当作条件，放在构造器当作查询
        productWithNumberQueryWrapper.eq(DaoConstant.INTO_HEADER.INTO_HEADER_ID,intoHeaderId);

        // 根据条件查询数据
        Page<ProductWithNumber> productWithNumberPage = iIntoItemService.selectProductWithNum(page,productWithNumberQueryWrapper);

        // 将数据放入结果集
        result.put(DaoConstant.MODEL.PRODUCTWITHNUMBER.MODEL_NAME,productWithNumberPage);

        //返回查询结果对象
        return Result.success(result);
    }

}

